package com.sgcc.pda.data.binder;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.sgcc.pda.CommonResultsFactory;
import com.sgcc.pda.common.aidl.CommonCallback;
import com.sgcc.pda.common.aidl.CommonParams;
import com.sgcc.pda.common.aidl.CommonResults;
import com.sgcc.pda.data.IDataManager;
import com.sgcc.pda.sdk.entity.table.UserInfo;
import com.sgcc.pda.sdk.utils.db.SharepreferenceUtil;

import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.List;


/**
 * 数据服务Data基础服务接口-封装给插件APP通过Binder调用
 *
 * @author Ben
 * @date 2019/06/06
 */
public class DataBinderUtil {
    /**
     * 成功字段
     */
    public static final String SUCCESS = "success";
    /**
     * 是否设置成功
     */
    public static final String IS_SUCCESS = "isSuccess";
    static final String CLASS_NAME = "com.sgcc.pda.data.binder.DataBinderUtil";

    private IDataManager mService = null;
    private boolean isBind = false;
    private Context mContext;
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IDataManager.Stub.asInterface(service);
            isBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
            mService = null;
        }
    };

    private DataBinderUtil() {
    }

    private static class Instance {
        private static final DataBinderUtil mInstance = new DataBinderUtil();
    }

    /**
     * 单例
     */
    public static DataBinderUtil getInstance() {
        return Instance.mInstance;
    }

    /**
     * 绑定掌机基础服务提供接口的AIDL服务
     *
     * @param context
     * @return 是否绑定
     */
    public boolean bind(Context context) {
        mContext = context;
        if (isBind) {
            return isBind;
        }
        Intent intent = new Intent("com.sgcc.pda.data.AIDL_DATA_SERVICE");
        intent.setPackage("com.sgcc.pda.mdrh.task.safe");
        try {
            isBind = context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        } catch (Exception e) {
            e.printStackTrace();
            isBind = false;
        }
        return isBind;
    }

    /**
     * 取消绑定掌机基础服务提供接口的AIDL服务
     *
     * @param context
     * @return 是否绑定
     */
    public void unbind(Context context) {
        try {
            context.unbindService(mConnection);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据方法名执行对应的方法
     *
     * @param params   参数
     * @param callback 回调
     * @return 结果
     */
    public CommonResults execute(CommonParams params, CommonCallback callback) {
        String methodName = params.getMethodName();
        try {
            // 通过反射调用方法，方法参数与返回值必须统一成（CommonParams，CommonCallback，CommonResults）
            Method method = getClass().getMethod(methodName, CommonParams.class, CommonCallback.class);
            return (CommonResults) method.invoke(this, params, callback);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResultsFactory.methodInvokeExceptionResults();
        }
    }

    /**
     * 将错误日志写入数据库
     *
     * @param params 接口参数 :
     *               userid
     *               detail
     *               data
     *               status
     *               etype
     * @return
     */
    public CommonResults saveExceptionInfo(CommonParams params, CommonCallback callback) throws RemoteException {
        String userid = params.getString("userid");
        String detail = params.getString("detail");
        String data = params.getString("data");
        String status = params.getString("status");
        String etype = params.getString("etype");

        boolean value = mService.saveExceptionInfo(userid, detail, data, status, etype);
        CommonResults results = CommonResultsFactory.successResults();
        results.addResult(IS_SUCCESS, value);
        return results;
    }

    /**
     * 获取微应用登录用户的相关信息，主要用于向H5应用 暴露 获取登录用户信息的接口
     * 【此方法使用的是contentprovider进行进程间通信】
     *
     * @param params
     * @param callback 本是同步获取，但异步返回也有数据
     * @return
     */
    public CommonResults getLoginUserInfo(CommonParams params, @Nullable CommonCallback callback) {
        CommonResults results = CommonResultsFactory.successResults();
        JSONObject userInfo = new JSONObject();
        try {
            List<UserInfo.User> users = SharepreferenceUtil.getPerson(mContext);
            String userCode = SharepreferenceUtil.getUserCode(mContext);
            if (users != null && users.size() != 0) {
                for (UserInfo.User item : users) {
                    if (TextUtils.equals(item.getUSER_CODE(), userCode)) {
                        userInfo.put("userId", item.getUSER_ID());//登录人账号
                        break;
                    }
                }
            }
            userInfo.put("userName", SharepreferenceUtil.getUserName(mContext));//安全单元用户名
            userInfo.put("userCode", userCode);//登录人账号
            userInfo.put("deptCode", SharepreferenceUtil.getDeptCode(mContext));//单位编号
            userInfo.put("deptName", SharepreferenceUtil.getDeptName(mContext));//单位名称
            userInfo.put("orgCode", SharepreferenceUtil.getOrgCode(mContext));//机构编号
            userInfo.put("orgName", SharepreferenceUtil.getOrgName(mContext));//机构名称
            userInfo.put("operatorNo", SharepreferenceUtil.getOperatorno(mContext));
            userInfo.put("operationNo", SharepreferenceUtil.getOperationno(mContext));
            userInfo.put("operator", SharepreferenceUtil.getOperator(mContext));//安全单元信息中的操作员代码
            userInfo.put("othAcctDept", SharepreferenceUtil.getOthAcctDept(mContext));//对端系统部门id
            userInfo.put("othAcctNo", SharepreferenceUtil.getOthAcctNo(mContext));//对端系统账号
            userInfo.put("othAcctOrg", SharepreferenceUtil.getOthAcctOrg(mContext));//对端系统供电单位
            userInfo.put("sysRoleId", SharepreferenceUtil.getSysRoleId(mContext));//系统角色id
            userInfo.put("sysRoleType", SharepreferenceUtil.getSysRoleType(mContext));//系统角色type
            userInfo.put("perOrgCode", SharepreferenceUtil.getPerOrgCode(mContext));//上级机构编码
            userInfo.put("orgType", SharepreferenceUtil.getOrgType(mContext));//供电单位类别
            results.addResult("userInfo", userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            results = CommonResultsFactory.customErrorResults("数据异常" + e.getLocalizedMessage() + userInfo.toString());
        }
        callback.callback(results);
        return results;
    }

    /**
     * 获取业务系统token
     */
    public CommonResults getSystemToken(CommonParams params, @Nullable CommonCallback callback) {
        CommonResults results = CommonResultsFactory.successResults();
        JSONObject systemTokenInfo = new JSONObject();
        try {
            String systemToken = SharepreferenceUtil.getSystemToken(mContext, params.getString("systemId"));
            systemTokenInfo.put("systemToken", systemToken);//业务系统token
            results.addResult("systemTokenInfo", systemTokenInfo);
        } catch (Exception e) {
            e.printStackTrace();
            results = CommonResultsFactory.customErrorResults("数据异常" + e.getLocalizedMessage() + systemTokenInfo.toString());
        }
        callback.callback(results);
        return results;
    }

    /**
     * 获取业务系统绑定的账号
     */
    public CommonResults getBindNumberInfo(CommonParams params, @Nullable CommonCallback callback) {
        CommonResults results = CommonResultsFactory.successResults();
        JSONObject systemNumberInfo = new JSONObject();
        try {
            String systemNumber = SharepreferenceUtil.getBindNumInfo(mContext, params.getString("systemId"));
            systemNumberInfo.put("systemNumber", systemNumber);//该业务系统绑定的账号
            results.addResult("systemNumberInfo", systemNumberInfo);
        } catch (Exception e) {
            e.printStackTrace();
            results = CommonResultsFactory.customErrorResults("数据异常" + e.getLocalizedMessage() + systemNumberInfo.toString());
        }
        callback.callback(results);
        return results;
    }
}
